import {
  PipeTransform,
  Injectable,
  ArgumentMetadata,
  BadRequestException, HttpStatus, HttpException
} from "@nestjs/common";
import { validate } from 'class-validator';
import { plainToInstance } from 'class-transformer';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, metadata: ArgumentMetadata) {
    const object = plainToInstance(metadata.metatype, value)
    const errors = await validate(object)
    if (errors.length > 0) {
      const messages = errors.map(err => ({
        name:err.property,
        message:Object.values(err.constraints).map(v=>v)
      }))
      throw new HttpException(messages[0].message.toString(), HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return value;
  }
}
